// pages/enterprise/user/setting-edit/phone/phone.js
import Behavior from "../behavior";
import {isInputEmpty, isPhoneNumber} from "../../../../utils/Util";
Component({
    /*
    * 组件间代码共享
    * */
    behaviors: [Behavior],

    /**
     * 组件的属性列表
     */
    properties: {
        value: {
            type: String,
            value: ""
        },
        smsLoading: { //验证码按钮状态
            type: Boolean,
            value: false
        },
        smsStart: {  //验证码倒计时
            type: Boolean,
            value: false
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _phone: "",
        _phoneErrorMsg: "",
        _sms: "",
        _smsErrorMsg: ""
    },

    observers: {
        "value": function (val) {
            if (val) {
                this.data._phone = val
            }
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {

        /*
        * 发送验证码按钮点击事件监听
        * */
        onSendSms: function () {
            if (!this._checkedPhone()) {
                return false
            } else {
                let phone = this.data._phone;
                this.triggerEvent("sendSms", {phone});
            }
        },

        /*
        * 点击保存按钮
        * */
        onSaveButton: function () {
            let loading = this.data.loading;
            let phone = this.data._phone;
            let sms = this.data._sms;
            if (loading) { //防重复
                return false
            } else if (!this._checkedPhone()) {  //手机号验证
                return false
            } else if (!isInputEmpty(sms)) {
                this.setData({_smsErrorMsg: "验证码不能为空！"})
            } else {
                this.triggerEvent("save", {phone, sms});
            }
        },

        /*
        * 验证
        * */
        _checkedPhone: function () {
            let phone = this.data._phone;
            if (!isInputEmpty(phone)) {
                this.setData({_phoneErrorMsg: "手机号码不能为空！"})
                return false
            } else if (!isPhoneNumber(phone)) {
                this.setData({_phoneErrorMsg: "手机号格式不正确！"})
                return false
            }
            return true
        }
    }
})
